package co.mobiless.noterecorder;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import co.mobiless.noterecorder.activities.EditNote;
import co.mobiless.noterecorder.activities.VerGrabacion;

public class ListaNotas extends ListActivity {
	private StorageData db;
	public static final int EDITAR_NOTA = Menu.FIRST;
	public static final int ELIMINAR_NOTA = Menu.FIRST+1;
	private Cursor mNotasCursor;
	private static final int NOTE_EDIT=1;
	private String idGrab;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.lista_notas);
        setTitle(R.string.titulo_lista_notas);
        db = new StorageData(this);
        db.open();
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
		if (extras == null) {
			return;
		}
		idGrab = extras.getString("idGrabacion");
		manejarIntent(intent);
        registerForContextMenu(getListView());
    }
    
    private void manejarIntent(Intent intent){
    	if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            fillData(query,idGrab);
        } else{
        	fillData("", idGrab);
        }
    	
    }

	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		manejarIntent(intent);
	}
    
    /*     @Override
	public boolean onCreateOptionsMenu(Menu menu) {
    	boolean result = super.onCreateOptionsMenu(menu);
        menu.add(0, EDITAR_NOTA, 0, R.string.editarNota);
        menu.add(0, ELIMINAR_NOTA, 1, R.string.eliminarNota);
		return result;
	}
    
    
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case EDITAR_NOTA:
                editarNota();
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    } */
    
    

	private void fillData(String query,String idGrab) {
        // Get all of the records from the database and create the item list
    	Integer idGrabacion=new Integer(idGrab);
    	mNotasCursor = db.fetchAllNotas(query,idGrabacion);
        startManagingCursor(mNotasCursor);
        
        String[] from = new String[] { StorageData.KEY_ROW_NAME_NOTE };
        int[] to = new int[] { R.id.nombreNota };
        
        // Now create an array adapter and set it to display using our row
        //SimpleCursorAdapter records = new SimpleCursorAdapter(this, R.layout.fila_notas, mNotasCursor, from, to);
        ImageCursorAdapter records = new ImageCursorAdapter(this, R.layout.fila_notas, mNotasCursor, from, to);
        setListAdapter(records);
       
    }	
	
	
	
	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
	
	

	@Override
	protected void onDestroy() {
		db.close();
		super.onDestroy();
	}

	@Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle(R.string.tituloMenuNota);
        menu.add(0, EDITAR_NOTA, 0, R.string.editarNota);
		menu.add(0, ELIMINAR_NOTA, 1, R.string.eliminarNota);
    }
	
	@Override
    public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info;
    	Cursor c;
        switch(item.getItemId()) {
            case EDITAR_NOTA:
                info = (AdapterContextMenuInfo) item.getMenuInfo();
                //c = mNotasCursor;
                //c.moveToPosition(info.position);
                Intent i = new Intent(this, EditNote.class);
                i.putExtra(StorageData.KEY_ROWID, info.id);
                //i.putExtra(StorageData.KEY_ROW_NAME_NOTE, c.getString(c.getColumnIndexOrThrow(StorageData.KEY_ROW_NAME_NOTE)));
                //i.putExtra(StorageData.KEY_ROW_ADITIONAL_TEXT_NOTE, c.getString(c.getColumnIndexOrThrow(StorageData.KEY_ROW_ADITIONAL_TEXT_NOTE)));
                startActivityForResult(i, NOTE_EDIT);
                fillData("",idGrab);
                return true;
            case ELIMINAR_NOTA:
                info = (AdapterContextMenuInfo) item.getMenuInfo();
                
                //Obtener la ubicaci�n del archivo png 
                c = mNotasCursor;
                c.moveToPosition(info.position);
                final String pathImage = c.getString(c.getColumnIndexOrThrow(StorageData.KEY_ROW_LOCATION_IMAGE_NOTE))+"/"+
                c.getString(c.getColumnIndexOrThrow(StorageData.KEY_ROW_NAME_ARCHIVE_IMAGE_NOTE));
                Log.d("pathNote", pathImage);
                final long idNote = info.id;
            	AlertDialog.Builder builder = new AlertDialog.Builder(this);
            	builder.setMessage("Est� seguro de borrar la nota?")
            	       .setCancelable(false)
            	       .setPositiveButton("Si", new DialogInterface.OnClickListener() {
            	           public void onClick(DialogInterface dialog, int id) {
            	        	   db.deleteNote(idNote, pathImage);
            	        	   Context context = getApplicationContext();
            	               Toast.makeText(context, "Nota borrada" , Toast.LENGTH_SHORT).show();
            	               fillData("",idGrab);
            	           }
            	       })
            	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
            	           public void onClick(DialogInterface dialog, int id) {
            	                dialog.cancel();
            	           }
            	       });
            	AlertDialog alert = builder.create();
            	builder.show();
                
                
                return true;
        }
        return super.onContextItemSelected(item);
    }
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        //Bundle extras = intent.getExtras();
        switch(requestCode) {
            case NOTE_EDIT:
            	if(resultCode==-1){//se puls� el bot�n guardar
	                /*Long rowId = extras.getLong(StorageData.KEY_ROWID);
	                if (rowId != null) {
	                    String editNombre = extras.getString(StorageData.KEY_ROW_NAME_NOTE);
	                    String editTextoAdicional = extras.getString(StorageData.KEY_ROW_ADITIONAL_TEXT_NOTE);
	                    if(db.updateNote(rowId, editNombre, editTextoAdicional)){
	                    	Toast.makeText(this,"Nota actualizada correctamente",2).show();
	                    }else{
	                    	Toast.makeText(this,"No se pudo actualizar la nota",2).show();
	                    }
	                }*/
	                fillData("",idGrab);
            	}else{ //se puls� el bot�n cancelar
            		
            	}
                break;
        }
    }
	
	/*Cuando se le da un click, abre la grabacion en el punto de la nota seleccionada
     * 
     *     
     */
	@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Intent i = new Intent(this, VerGrabacion.class);
		i.putExtra("idNota", Long.toString(id));
		i.putExtra("idGrabacion", idGrab);
		startActivity(i);
    }
    
    
}
